package com.bw.controller;

import com.alibaba.fastjson.JSON;
import com.bw.entity.UserInfo;
import com.bw.mapper.UserMapper;
import org.aspectj.lang.annotation.Around;
import org.spring.kun.common.Md5Utils;
import org.spring.kun.common.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.concurrent.TimeUnit;

@Controller
public class LoginController {


    @Autowired
    UserMapper userMapper;

    @Autowired
    RedisTemplate redisTemplate;

    @RequestMapping("/loginPage.do")
    public String loginPage() {
        return "login";
    }


    @RequestMapping("/login.do")
    public String login(@Valid UserInfo loginUser, BindingResult result, Model model, HttpServletResponse response) {

        if (result.hasErrors()){
            model.addAttribute("error",result.getAllErrors().get(0).getDefaultMessage());

            return "login";

        }
        // 用户名是否存在
        UserInfo userFromDB =   userMapper.selectByName(loginUser.getName());
        if (userFromDB == null){
            model.addAttribute("error","用户名不存在");
            return "login";
        }

        String loginUserPassword = loginUser.getPassword();

        String salt = userFromDB.getSalt();
        String password = userFromDB.getPassword();

        String md5String = Md5Utils.getMD5String(loginUserPassword + salt);

        if (!md5String.equals(password)){
            model.addAttribute("error","密码错误");
            return "login";
        }

        // 加密用户信息 制作学生证  放入cookie 返回给浏览器 让浏览器保存

        TokenUtils.responseTokenByCookie(userFromDB,response);
        //使用Redis保存登录的用户信息，设置过期时间为cookie的过期时间
        redisTemplate.opsForValue().set("name", JSON.toJSONString(userFromDB),30, TimeUnit.MINUTES);
        // 绑定之后 再次登录可以展示出昵称和头像
        model.addAttribute("nickName",userFromDB.getNickName());
        model.addAttribute("avatarUrl",userFromDB.getAvatarUrl());
        return "success";
    }



}
